<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="学期" prop="semId">
        <el-select v-model="queryParams.semId" filterable clearable placeholder="请选择学期">
          <el-option
            v-for="item in semsterList"
            :key="item.id"
            :label="item.title"
            :value="item.id"
            size="small">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态" prop="checkStatus">
        <el-select v-model="queryParams.checkStatus" placeholder="请选择审核状态" clearable size="small">
          <el-option
            v-for="dict in checkStatusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="multiple"
          @click="handleCheck1"
          v-hasPermi="['education:eduExchange:check']"
        >审核通过</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleCheck2"
          v-hasPermi="['education:eduExchange:check']"
        >审核不通过</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-if="importable"
          type="info"
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['education:eduExchange:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['education:eduExchange:export']"
        >导出</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="eduExchangeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="学期" align="center" prop="semName" />
      <el-table-column label="班级" align="center" prop="className" />
      <el-table-column label="课程" align="center" prop="courseName1" />
      <el-table-column label="上课日期" align="center" prop="fromDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.fromDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上课节次" align="center" prop="fromSectionName" />
      <el-table-column label="对调教师" align="center" prop="teacherName2" />
      <el-table-column label="对调课程" align="center" prop="courseName2" />
      <el-table-column label="新上课日期" align="center" prop="toDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.toDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="新上课节次" align="center" prop="toSectionName" />
      <el-table-column label="添加时间" align="center" prop="addTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.addTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="checkStatus" :formatter="checkStatusFormat" />
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改调课管理对话框 -->
    <el-dialog  :close-on-click-modal="false" :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="班级" prop="classId">
          <el-select v-model="form.classId" filterable clearable placeholder="请选择班级" @change="loadClassTask()">
            <el-option
              v-for="item in formClazzList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
              size="small">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="本人课程" prop="fromDetailId">
          <el-select v-model="form.fromDetailId" filterable clearable placeholder="课程">
            <el-option v-if="item.teacherId == teacherId"
              v-for="item in classTaskList"
              :key="item.id"
              :label="item.courseName"
              :value="item.id"
              size="small">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上课日期" prop="fromDate">
          <el-date-picker clearable size="small" style="width: 200px" v-model="form.fromDate" type="date" value-format="yyyy-MM-dd"
            placeholder="选择上课日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="上课节次" prop="fromSection">
          <el-select v-model="form.fromSection" placeholder="请选择节次" clearable size="small">
            <el-option
              v-for="dict in sectionList"
              :key="dict.id"
              :label="dict.title"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="对方课程" prop="toDetailId">
          <el-select v-model="form.toDetailId" filterable clearable placeholder="课程">
            <el-option v-if="item.teacherId != teacherId"
              v-for="item in classTaskList"
              :key="item.id"
              :label="item.courseName"
              :value="item.id"
              size="small">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="新上课日期" prop="toDate">
          <el-date-picker clearable size="small" style="width: 200px" v-model="form.toDate" type="date" value-format="yyyy-MM-dd"
            placeholder="选择新上课日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="新上课节次" prop="toSection">
          <el-select v-model="form.toSection" placeholder="请选择节次" clearable size="small">
            <el-option
              v-for="dict in sectionList"
              :key="dict.id"
              :label="dict.title"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog  :close-on-click-modal="false" :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listEduExchange, getEduExchange, delEduExchange, addEduExchange, updateEduExchange, exportEduExchange, checkExchange, importTemplate } from "@/api/education/eduExchange";
import { myEduTask, listEduTask} from "@/api/education/eduTask";
import { getToken } from "@/utils/auth";
import { selectSemster} from "@/api/base/semster";
import { selectClazz } from "@/api/base/clazz";
import { selectSection} from "@/api/base/section";
export default {
  name: "MyExchange",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      importable: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 调课管理表格数据
      eduExchangeList: [],
      //学期
      semsterList: [],
      // 节次数据
      sectionList: [],
      // 班级表格数据
      formClazzList: [],
      // 班级表格数据
      queryClazzList: [],
      // 个人教学任务数据
      myTaskList: [],
      // 班级教学任务数据
      classTaskList: [],
      // 审核状态字典
      checkStatusOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fromDetailId: null,
        toDetailId: null,
        fromDate: null,
        toDate: null,
        addTime: null,
        addUser: null
      },
      semdId: null,
      teacherId: null,
      // 表单参数
      form: {},
      // 导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/education/eduExchange/importData"
      },
      // 表单校验
      rules: {
        fromDetailId: [
          { required: true, message: "原课程不能为空", trigger: "blur" }
        ],
        toDetailId: [
          { required: true, message: "新课程不能为空", trigger: "blur" }
        ],
        fromDate: [
          { required: true, message: "上课日期不能为空", trigger: "blur" }
        ],
        toDate: [
          { required: true, message: "新上课日期不能为空", trigger: "blur" }
        ],
        classId: [
          { required: true, message: "班级不能为空", trigger: "blur" }
        ],
        fromSection: [
          { required: true, message: "上课节次不能为空", trigger: "blur" }
        ],
        toSection: [
          { required: true, message: "新上课节次不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("check_status").then(response => {
      this.checkStatusOptions = response.data;
    });
    selectSection({'status':1}).then(response => {
        this.sectionList = response.rows;
        this.total = response.total;
      });
    selectSemster({'status':1}).then(response => {
      this.semsterList = response.rows;
      for(var i=0;i<response.rows.length;i++){
        if(response.rows[i]['isCurrent'] == 'Y') this.semdId = response.rows[i]['id'];
      }
    });
  },
  methods: {
    /** 查询调课管理列表 */
    getList() {
      this.loading = true;
      listEduExchange(this.queryParams).then(response => {
        this.eduExchangeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 审核状态字典翻译
    checkStatusFormat(row, column) {
      return this.selectDictLabel(this.checkStatusOptions, row.checkStatus);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        semId: null,
        classId: null,
        fromDetailId: null,
        toDetailId: null,
        fromDate: null,
        toDate: null,
        addTime: null,
        addUser: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    loadMyTask() {
      this.form.semId = this.semdId;
      myEduTask({semId:this.semdId}).then(response => {
        this.myTaskList = response.rows;
        this.formClazzList = {};
        for(var i=0;i<this.myTaskList.length;i++){
          this.teacherId = this.myTaskList[i]['teacherId'];
          if(!this.formClazzList[this.myTaskList[i]['classId']])
          this.formClazzList[this.myTaskList[i]['classId']] = {id:this.myTaskList[i]['classId'], title:this.myTaskList[i]['className']};
        }
      });
    },
    loadClassTask() {
      listEduTask({semId:this.semdId, classId:this.form.classId}).then(response => {
        this.classTaskList = response.rows;
        this.formClazzList = {};
      });
    },
    filterCourse() {
      this.formCourseList = {};
      for(var i=0;i<this.taskList.length;i++){
        if(!this.formClazzList[this.taskList[i]['courseId']])
        this.formCourseList[this.taskList[i]['courseId']] = {id:this.taskList[i]['courseId'], title:this.taskList[i]['courseName']}
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.loadMyTask();
      this.title = "添加调课";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getEduExchange(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改调课";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateEduExchange(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addEduExchange(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除调课管理编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delEduExchange(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有调课管理数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportEduExchange(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },
    /** 审核通过按钮操作 */
    handleCheck1 (row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认将选中的申请信息设置为 审核通过 状态吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return checkExchange({batchs:ids, checkStatus: '1'});
        }).then(() => {
          this.getList();
          this.msgSuccess("操作成功");
        })
    },
    /** 审核不通过按钮操作 */
    handleCheck2 (row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认将选中的申请信息设置为 审核不通过 状态吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return checkExchange({batchs:ids, checkStatus: '2'});
        }).then(() => {
          this.getList();
          this.msgSuccess("操作成功");
        })
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "调课申请导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.download(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
